package tangmukeji.com.rxjava2retrofit2.api;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import tangmukeji.com.rxjava2retrofit2.base.BaseResponse;

/**
 * Created by Administrator on 2018/3/22 0022.
 * 对返回值的封装，以及对请求效果的封装
 */

public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    private Context mContext;
    private ProgressDialog mProgressDialog;
    private Disposable mDisposable;

    //默认无效果的请求（不带进度条）
    protected BaseObserver(Context mContext) {
        this.mContext = mContext.getApplicationContext();
    }

    //带进度条的请求
    protected BaseObserver(Context mContext, boolean isShowProgress) {
        this.mContext = mContext.getApplicationContext();
        if (isShowProgress) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    mDisposable.dispose();
                }
            });
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
    }

    @Override
    public void onNext(BaseResponse<T> value) {
        //对数据的封装
        if (value.getCode() == 200) {
            T t = value.getData();
            onHandleSuccess(t);
        } else {
            onHandleError(value.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onComplete() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    protected abstract void onHandleSuccess(T t);

    protected void onHandleError(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }
}
